<template>
  <page-wrap stay-still back hide-tab title="教育背景">
    <view class="form-wrap" :style="'margin-bottom:' + inputBottom + 'px;'">
      <u-form :model="form" ref="uForm" label-position="top" class="form">
        <block v-for="(item, index) in formList" :key="index">
          <view
            class="form-item-wrap"
            @click.capture="handleSelect($event, item, index)"
          >
            <u-form-item
              :class="[{ pick: item.comp }, { multiple: item.multiple }]"
              :label="item.label"
              :prop="item.prop"
              :border-bottom="!item.hideBorderBottom"
            >
              <!-- textarea -->
              <my-textarea
                v-if="!item.comp && item.type === 'textarea'"
                class="form-text"
                :value="form[item.prop]"
                :placeholder="item.inputPlaceholder"
                :maxlength="item.maxlength"
                auto-height
                show-word-limit
                @update:value="handleClear($event, item)"
                @board-change="handleBottom"
              ></my-textarea>
              <u-input
                v-else
                :class="[
                  'form-input',
                  { textarea: item.inputType === 'textarea' },
                ]"
                v-model="form[item.prop]"
                :disabled="!!item.comp"
                :placeholder="item.inputPlaceholder"
                :type="item.inputType"
                :height="item.height"
                :maxlength="item.maxlength || 150"
                :clearable="false"
                :id="item.prop"
              />
              <text v-if="item.multiple">~</text>
              <u-input
                v-if="item.multiple"
                class="form-input"
                v-model="form[item.prop2]"
                :disabled="!!item.comp"
                :placeholder="item.inputPlaceholder2"
                :clearable="false"
                @click="handleMultipleSelect(item)"
                :id="item.prop2"
              />

              <!-- 下拉选择 -->
              <u-select
                class="form-select"
                v-model="item.show"
                :list="item.data"
                :mode="item.mode || 'single-column'"
                v-if="item.comp === 'select'"
                @confirm="handleConfirm($event, item)"
              ></u-select>
              <!-- 时间选择 -->
              <u-picker
                class="form-time"
                mode="time"
                v-model="showTime"
                :params="item.param"
                :start-year="item.start"
                :end-year="item.end"
                :default-time="form[tapTarget] || ''"
                v-if="item.comp === 'time'"
                @confirm="handleConfirm($event, item)"
              ></u-picker>
            </u-form-item>
            <!-- <view v-if="item.showWords" class="content-words"
              >{{
                1000 - ((form[item.prop] && form[item.prop].length) || 0)
              }}字</view
            > -->
          </view>
        </block>
      </u-form>
    </view>
    <view class="page-action">
      <view class="btn-delete" v-if="eduId && !isLast">
        <u-button
          :hair-line="false"
          :plain="true"
          :custom-style="btnSaveStyle"
          @click="handleDelete"
          >删除</u-button
        >
      </view>
      <view class="btn-save">
        <u-button type="primary" :custom-style="btnStyle" @click="handleSave"
          >保存</u-button
        >
      </view>
    </view>
  </page-wrap>
</template>

<script>
import { updateEducation, deleteEducation, getResumeData } from "@/api/index";
import { eduList } from "@/utils/data";
import { formatTime } from "@/utils/handle";
import MyTextarea from "../components/MyTextarea.vue";
import ShareMixin from "@/mixins/share";
import { throttle } from "lodash";
export default {
  mixins: [ShareMixin],
  components: {
    MyTextarea,
  },
  data() {
    return {
      isLast:
        getApp().globalData.userInfo.personEdusArr &&
        getApp().globalData.userInfo.personEdusArr.length <= 1,
      inputBottom: 0,
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      eduId: "",
      showXueli: false,
      showSelect: false,
      showTime: false,
      zyList: [],
      info: {},
      form: {},
      formList: [
        {
          label: "学校名称",
          prop: "school",
          inputPlaceholder: "请输入学校名称",
        },
        {
          label: "学历",
          prop: "eduId_xueli",
          propVal: "eduId",
          comp: "select",
          show: false,
          inputPlaceholder: "请选择学历",
          data: eduList,
        },
        {
          label: "专业名称",
          prop: "zye",
          propPVal: "zym",
          inputPlaceholder: "请选择专业",
          comp: "select",
          data: [],
          mode: "mutil-column-auto",
          show: false,
        },
        {
          label: "就读时间",
          multiple: true,
          prop: "startdate",
          prop2: "stopdate",
          inputPlaceholder: "请选择开始时间",
          inputPlaceholder2: "请选择结束时间",
          comp: "time",
          show: "showTime",
          setProp2: false,
          param: {
            year: true,
            month: true,
            day: true,
            hour: false,
            minute: false,
            second: false,
          },
          start: new Date().getFullYear() - 70,
          end: 2100,
        },
        {
          prop: "edus",
          type: "textarea",
          inputPlaceholder: "简要对背景进行描述",
          height: "260",
          maxlength: 1000,
          showWords: true,
          hideBorderBottom: true,
        },
      ],
      btnSaveStyle: {
        border: "none",
        backgroundColor: "#E9ECEF",
      },
      btnStyle: {
        border: "none",
      },
      rules: {
        school: [
          {
            required: true,
            message: "请输入学校名称",
          },
        ],
        eduId_xueli: [
          {
            required: true,
            message: "请选择学历",
          },
        ],
        zye: [
          {
            required: true,
            message: "请选择专业",
          },
        ],
        startdate: [
          {
            validator: this.testStartDate,
          },
        ],
      },
      tapTarget: "",
    };
  },
  watch: {
    info: {
      handler(val) {
        if (val.personEdusArr) {
          let item = val.personEdusArr.find((ele) => ele.edusId === this.eduId);
          this.form = {
            edusId: item.edusId,
            school: item.school,
            eduId: item.eduId,
            eduId_xueli: this.handleXueli(item.eduId),
            startdate: item.startdate,
            stopdate: item.stopdate,
            edus: item.edus,
            zym: item.zym,
            zye: item.zye,
          };
        }
      },
      deep: true,
      immediate: true,
    },
    showTime(val) {
      if (!val) {
        this.formList.forEach((item) => {
          if (item.setProp2) {
            item.setProp2 = false;
          }
        });
      }
    },
    inputBottom(val) {
      if (val) {
        this.$nextTick(() => {
          uni.pageScrollTo({
            scrollTop: 99999,
            duration: 0,
          });
        });
      }
    },
  },
  mounted() {
    this.formList[1].data = eduList.slice(1, eduList.length);
    getFileByUrl('https://img3.job1001.com/ypMp/elan/files/major.json').then(res => {
      this.formList[2].data = res;
    })
  },
  onLoad(options) {
    if (options.id) {
      this.eduId = options.id;
      this.getResumeData();
    }
  },
  // onShareAppMessage() {
  //   return {
  //     title: this.$selfName,
  //     path: "/pages/index/index",
  //   };
  // },
  // onShareTimeline() {
  //   return {
  //     title: this.$selfName,
  //     path: "/pages/index/index",
  //   };
  // },
  methods: {
    testStartDate(rule, value, callback) {
      if (!value) {
        return callback("请选择开始时间");
      } else if (!this.form.stopdate) {
        return callback("请选择结束时间");
      } else if (value >= this.form.stopdate) {
        return callback("起止时间有误");
      }
      return true;
    },
    handleBottom(e) {
      this.inputBottom = e > 130 ? e - 130 : 0;
    },
    handleClear(e, item) {
      this.$set(this.form, item.prop, e);
    },
    getResumeData() {
      if (
        !getApp().globalData.resumeInfo ||
        !getApp().globalData.resumeInfo.id
      ) {
        let param = {
          personId: this.personId,
          conditionArr: JSON.stringify({
            is_mp: 1,
          }),
        };
        getResumeData(param).then((res) => {
          this.info = res;
        });
      } else {
        this.info = JSON.parse(JSON.stringify(getApp().globalData.resumeInfo));
      }
    },

    handleSave: throttle(function () {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.saveEdu();
        }
      });
    },3000),

    saveEdu() {
      // if (
      //   this.form.startdate > formatTime(new Date(), "yyyy-MM-dd") ||
      //   this.form.stopdate > formatTime(new Date(), "yyyy-MM-dd")
      // ) {
      //   return uni.showToast({ icon: "none", title: "就读时间有误" });
      // }
      var param = {};
      param.person_id = this.personId;
      var conditionArr = {};
      conditionArr.edus = {};
      //校验
      let list = this.form;

      if (list.edusId != "undefined") {
        conditionArr.edus.edusId = list.edusId;
      }
      conditionArr.edus.school = list.school;
      conditionArr.edus.eduId_xueli = list.eduId_xueli;
      conditionArr.edus.eduId = list.eduId;
      conditionArr.edus.startdate = list.startdate;
      conditionArr.edus.stopdate = list.stopdate;
      conditionArr.edus.edus = list.edus;
      conditionArr.edus.zye = list.zye;
      conditionArr.edus.zym = list.zym;

      param.conditionArr = JSON.stringify(conditionArr);

      updateEducation(param).then((res) => {
        if (res.code == 200) {
          uni.showToast({
            icon: "none",
            title: "保存成功",
            complete() {
              setTimeout(() => {
                uni.navigateBack();
              }, 1500);
            },
          });
        } else {
          uni.showToast({ icon: "none", title: res.status_desc });
        }
      });
    },
    handleDelete() {
      uni.showModal({
        title: "温馨提示",
        content: `确认删除教育背景？`,
        success: (modalRes) => {
          if (modalRes.confirm) {
            if (!this.form.edusId) return;
            var params = {
              array: JSON.stringify({
                personId: this.personId,
                edusId: this.form.edusId,
              }),
            };
            deleteEducation(params).then((res) => {
              if (res.code == 200) {
                uni.showToast({
                  icon: "none",
                  title: "删除成功",
                  complete() {
                    setTimeout(() => {
                      uni.navigateBack();
                    }, 1500);
                  },
                });
              } else {
                uni.showToast({ icon: "none", title: res.status_desc });
              }
            });
          }
        },
      });
    },
    handleSelect($event, item, index) {
      if (item.comp == "select") {
        this.$set(item, "show", true);
      } else if (item.comp) {
        this[item.show] = true;
        this.tapTarget = $event.target.id;
      }
    },
    handleMultipleSelect(item) {
      if (item.multiple) {
        this.$set(item, "setProp2", true);
      }
    },
    handleConfirm(e, item) {
      if (Array.isArray(e)) {
        this.$set(this.form, item.prop, e[0].label);
        if (item.propVal) {
          this.$set(this.form, item.propVal, e[0].value);
        }
        if (e.length > 1 && item.propPVal) {
          this.$set(this.form, item.prop, e[1].label);
          this.$set(this.form, item.propPVal, e[0].value);
        }
      } else {
        let time = `${e.year}-${e.month}-${e.day}`;
        if (item.setProp2) {
          this.$set(this.form, item.prop2, time);
          this.$set(item, "setProp2", false);
          return;
        }
        this.$set(this.form, item.prop, time);
      }
    },
    handleReturn([data, name], index) {
      if (Array.isArray(name) && Array.isArray(data)) {
        name.forEach((ele, idx) => {
          this.$set(this.form, ele, data[idx]);
        });
        if (!index) {
          this.$set(this.formList[index], "activeParent", data[2]);
        }
      } else {
        this.$set(this.form, name, data);
      }
      this[this.formList[index].show] = false;
    },
    handleXueli(eduId) {
      let itme = eduList.find((ele) => {
        return ele.value == eduId;
      });
      return itme.label;
    },
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
};
</script>

<style lang="scss">
$img-base-resume: $img-base + "resume/";
.form-wrap {
  flex-grow: 1;
  ::v-deep .u-form {
    flex-grow: 1;
    padding-top: 0;
    margin: 32rpx 32rpx 0;
    padding: 32rpx 32rpx 0;
    background-color: $uni-bg-color;
    border-radius: $uni-border-radius-big;
    .form-text {
      display: block;
      width: calc(100vw - 128rpx);
      box-sizing: border-box;
      .textarea-input {
        background-color: #f8f9fb;
        border-radius: $uni-border-radius-big;
        textarea,
        .textarea {
          height: 260rpx !important;
          font-size: $uni-font-size-sm;
        }
        .placeholder {
          font-size: $uni-font-size-sm;
        }
      }
    }
    .textarea {
      background-color: #f8f9fb;
      border-radius: $uni-border-radius-big;
      .u-input {
        background-color: #f8f9fb;
        border-radius: $uni-border-radius-big;
      }
    }
    .u-input__textarea {
      padding: 24rpx 32rpx;
      font-size: $uni-font-size-nor;
    }

    .content-words {
      margin-right: 10rpx;
      text-align: right;
      color: $uni-text-color-888;
      font-size: $uni-font-size-sm;
    }
  }
}
</style>
